<template>
  <ProTable
    ref="tableRef"
    :fetchListApi="_getUpgradeList"
    :columns="columns"
    row-key="upgradeId"
    :rowSelection="rowSelection"
  >
    <template #toolbars>
      <Space>
        <b-button icon="add" @click="onAdd()">新增</b-button>
        <b-button
          icon="delete"
          @click="onDelete()"
          code="packageManage:remove"
          :disabled="!selectRows.length"
          >删除</b-button
        >
      </Space>
    </template>
    <template #modelAlwaysVOS="{ record }">
      <Tree
        v-if="record.modelAlwaysVOS && record.modelAlwaysVOS.length"
        :tree-data="record.modelAlwaysVOS"
        :field-names="fileNames"
      />
    </template>
    <template #operation="{ record }">
      <template v-if="record.isAudit != '0'">
        <b-button
          icon="edit"
          type="link"
          code="packageManage:edit"
          @click="onUpdate(record)"
        >
          编辑</b-button
        >
        <b-button
          icon="examine"
          type="link"
          code="packageManage:audit"
          @click="onAudit(record)"
        >
          审核</b-button
        >
      </template>
      <b-button
        icon="detail"
        type="link"
        v-else
        code="packageManage:show"
        @click="onLook(record)"
      >
        查看</b-button
      >
    </template>
  </ProTable>
  <FormModal :items="items"> </FormModal>
</template>

<script setup lang="tsx">
import { computed, onMounted, ref } from 'vue';
import {
  Input,
  Modal,
  Space,
  Tag,
  Tree,
  TreeProps,
  TreeSelect,
  message,
} from 'ant-design-vue';
import { ProFormProps } from '@/components/ProForm';
import { ProTable, ProTableProps } from '@/components/ProTable/index';
import { useFormModal } from '@/hooks/formModal';
import { auditEnum, packageTypeEnum, packageTypeOption } from '@/constant/push';
import {
  deleteUpgrade,
  getUpgradeDetail,
  getUpgradeList,
  modelTree,
  packageAudit,
  upgradeInfo,
} from '@/api/config';

const tableRef = ref();

const _getUpgradeList = async (params: any) => {
  const res = await getUpgradeList(params);
  res.rows.forEach((item: any) => {
    if (item.modelAlwaysVOS) {
      item.modelAlwaysVOS.forEach((model: any) => {
        model.typeName = `${model.typeName}(${model.modeName.length})`;
        model.modeName = model.modeName.map((name: any) => {
          return {
            typeName: name,
          };
        });
      });
    }
  });
  return { rows: [...res.rows], total: res.total || 0 };
};

const fileNames: TreeProps['fieldNames'] = {
  title: 'typeName',
  children: 'modeName',
};

const selectRows = ref<any[]>([]);
const rowSelection = computed<ProTableProps['rowSelection']>(() => {
  return {
    onChange(values, selectedRows) {
      selectRows.value = selectedRows;
    },
  };
});

const modelTreeData = ref([]);
onMounted(() => {
  modelTree().then((res: any) => {
    modelTreeData.value = res.data;
  });
});

const columns = computed<ProTableProps['columns']>(() => [
  {
    title: '版本类型',
    dataIndex: 'deviceType',
    valueEnum: packageTypeEnum,
  },
  {
    title: '升级包名称',
    dataIndex: 'upgradeName',
  },
  {
    title: '设备型号',
    dataIndex: 'modelAlwaysVOS',
    hideInSearch: true,
    width: 120,
  },
  {
    title: '设备型号',
    dataIndex: 'modelIds',
    hideInTable: true,
    customSearchRender(state) {
      return (
        <TreeSelect
          v-model:value={state.modelIds}
          fieldNames={{
            children: 'childs',
            label: 'model',
            value: 'modelId',
          }}
          placeholder='请选择'
          treeData={modelTreeData.value}
          treeCheckable={true}
          maxTagCount={1}
          allowClear={true}
        />
      );
    },
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    hideInSearch: true,
  },
  {
    title: '审核状态',
    dataIndex: 'isAudit',
    hideInSearch: true,
    valueEnum: auditEnum,
    width: 100,
    customRender({ text }) {
      return (
        <Tag color={text == '0' ? 'success' : 'error'}>
          {auditEnum[text as keyof typeof auditEnum]}
        </Tag>
      );
    },
  },
  {
    title: '审核时间',
    dataIndex: 'auditTime',
    hideInSearch: true,
  },
  {
    title: '审核人',
    dataIndex: 'auditBy',
    hideInSearch: true,
  },
  {
    title: '操作',
    dataIndex: 'operation',
    hideInSearch: true,
    fixed: 'right',
    width: 200,
  },
]);

const items = computed<ProFormProps['items']>(() => [
  {
    label: '版本类型',
    type: 'select',
    field: 'deviceType',

    rules: [
      {
        required: true,
        message: '请选择版本类型',
        trigger: 'blur',
      },
    ],
    props: {
      placeholder: '请选择版本类型',
      options: packageTypeOption,
    },
  },
  {
    label: '升级包名称',
    type: 'input',
    field: 'upgradeName',
    rules: [
      {
        required: true,
        message: '请输入升级包名称',
        trigger: 'blur',
      },
    ],
    props: {
      placeholder: '请输入升级包名称',
    },
  },
  {
    label: '设备型号',
    type: 'input',
    field: 'modelIds',
    rules: [
      {
        required: true,
        message: '请选择设备型号',
        trigger: 'blur',
      },
    ],
    customRender(formState) {
      return (
        <TreeSelect
          v-model:value={formState.modelIds}
          fieldNames={{
            children: 'childs',
            label: 'model',
            value: 'modelId',
          }}
          placeholder='请选择'
          treeData={modelTreeData.value}
          treeCheckable={true}
          maxTagCount={1}
          allowClear={true}
        />
      );
    },
  },
]);
const { FormModal, open } = useFormModal({
  size: 'small',
  column: 1,
  formProps: { labelCol: { span: 4 } },
});

const onAdd = async () => {
  open({
    title: '新增',
    defaultValue: {},
    serviceApi: async (params: any): Promise<any> => {
      await upgradeInfo(params);
      tableRef.value.refresh();
    },
  });
};

const onUpdate = async (record: any) => {
  let response = await getUpgradeDetail(record.upgradeId);
  open({
    title: (type) => (type === 'info' ? '详情' : '编辑'),
    modalType: 'info',
    defaultValue: { ...(response.data as object) },
    serviceApi: async (params: any): Promise<any> => {
      await upgradeInfo(params);
      tableRef.value.refresh();
    },
  });
};

const sleep = (cb) => {
  setTimeout(() => {
    cb();
  }, 500);
};
const onAudit = async (record: any) => {
  Modal.confirm({
    title: '系统提示',
    centered: true,
    content: `确认审核通过？`,
    onOk: async () => {
      await packageAudit({ upgradeId: record.upgradeId, isAudit: '0' });
      sleep(() => tableRef.value.refresh());
      message.success('审核成功');
    },
  });
};
const onLook = async (record: any) => {
  let response = await getUpgradeDetail(record.upgradeId);
  open({
    title: '详情',
    modalType: 'info',
    defaultValue: { ...(response.data as object) },
    hasEditPermission: false,
    serviceApi: () => Promise.resolve(''),
  });
};
const sleep = (cb) => {
  setTimeout(() => {
    cb();
  }, 500);
};

const onDelete = async (record: any) => {
  const upgradeIds = selectRows.value.map((item) => item.upgradeId);
  Modal.confirm({
    title: '系统提示',
    centered: true,
    content: `确认删除当前项？`,
    onOk: async () => {
      await deleteUpgrade(upgradeIds.join());
      sleep(() => tableRef.value.refresh());
      message.success('删除成功');
    },
  });
};
</script>
